package com.duowan.cms.intf.piclib;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.duowan.cms.intf.Constants;
import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.NetUtil;
import com.duowan.cms.common.util.StringUtil;
@Service("picLibRemoteService")
public class PicLibServiceImpl implements PicLibRemoteService {

	@Override
	public List<TujiInfo> getList(String alias, Integer offset, Integer pageSize, Integer sort, String tag) throws BaseCheckedException {
		String paramStr = this.getUrlParam(alias, offset, pageSize, sort, tag);
		String responseContent = NetUtil.getHttpRequest(paramStr, Constants.TU_API_URL, Constants.EXPIRE_SECONDS);
		if (StringUtil.isEmpty(responseContent)) {
			return null;
		}
		return this.json2TujiInfoList(responseContent);
	}

	private String getUrlParam(String alias, Integer offset, Integer pageSize, Integer sort, String tag) {
		StringBuilder urlParamBuilder = new StringBuilder();
		urlParamBuilder.append("r=api/zq&alias="+alias);
		if(null != pageSize)
		urlParamBuilder.append("&page="+pageSize);
		if(null != sort)
		urlParamBuilder.append("&sort="+sort);
		if(null != offset)
		urlParamBuilder.append("&num="+offset);
		if(!StringUtil.isEmpty(tag))
		urlParamBuilder.append("&tag="+tag);
		return urlParamBuilder.toString();
	}
	/**
	 * 转换json数组为list
	 * @param jsonArr
	 * @return
	 * @throws JSONException
	 */
	private List<TujiInfo> json2TujiInfoList(String jsonStr) {
		JSONArray jsonArr = JSONArray.fromObject(jsonStr);  
		List<TujiInfo> list = null;
		if (null != jsonArr && jsonArr.size() > 0) {
			list = new ArrayList<TujiInfo>();
			for (int i = 0; i < jsonArr.size(); i++) {
				JSONObject json = jsonArr.getJSONObject(i);
				TujiInfo Tuji = (TujiInfo)JSONObject.toBean(json, TujiInfo.class);
				list.add(Tuji);
			}
		}
		return list;
	}
}
